/**
 * @desc 工具类
 * @author liqiang
 * @company fivefire
 * @date 13 Nov 2017
 */

'use strict'

const config = require('../config')
const logger = require('./logger')

// oops noop
function noop() {}

/**
 * 校验手机号码
 * @param  {} phone=''  手机号码
 */
function isPhoneNo(phone = '') {
  return /^1\d{10}$/.test(phone)
}

/**
 * 判断是否是空对象
 * @param  {} obj={}  待判断对象
 */
function isEmptyObject(obj = {}) {
  for (let key in obj) {
    return !1
  }
  return !0
}

/**
 * 格式化经纬度
 * @param  {} longitude
 * @param  {} latitude
 */
function formatLocation(longitude, latitude) {
  if (typeof longitude === 'string' && typeof latitude === 'string') {
    longitude = parseFloat(longitude)
    latitude = parseFloat(latitude)
  }

  longitude = longitude.toFixed(2)
  latitude = latitude.toFixed(2)

  return {
    longitude: longitude.toString().split('.'),
    latitude: latitude.toString().split('.')
  }
}
// 格式化日期
function formatTime(date) {  
  var year = date.getFullYear()  
  var month = date.getMonth() + 1  
  var day = date.getDate()  
  
  var hour = date.getHours()  
  var minute = date.getMinutes()  
  var second = date.getSeconds()  

  return [year, month, day].map(formatNumber).join('/') //+ ' ' + [hour, minute, second].map(formatNumber).join(':')  
}
function parseNumber(num) {
    let numLength = num.toString().length;
    let numResult ;
    if(numLength < 4){
        numResult = num;
    }
    if(numLength == 4){//千
        numResult = num /1000;
        if(numResult.toString().length >1){
            numResult = numResult.toFixed(1);
        }
        numResult = numResult+"k";
    }
    if(numLength == 5){//万

    }
    if(numLength == 6){//十万

    }
    if(numLength == 7){//百万

    }
    return numResult;
}

function formatDate(date) {  
  var year = date.getFullYear()  
  var month = date.getMonth() + 1  
  var day = date.getDate()  
  
  var hour = date.getHours()  
  var minute = date.getMinutes()  
  var second = date.getSeconds()  

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')  
}  
  
function formatNumber(n) {  
  n = n.toString()  
  return n[1] ? n : '0' + n  
}
/**
 * 显示Modal，颜色匹配
 * @param  {String | Object} params={} Modal参数
 */
function showModal(params = {}) {
  if (typeof params === 'string') {
    params = {
      content: params
    }
  }
  return wx._showModal(Object.assign({
    title: '提示',
    showCancel: false,
    confirmText: '我知道了',
    confirmColor: config.baseColor
  }, params))
}

/**
 * 设置/移除 本地token
 * @param  {} val       token值
 */
function setLocalToken(val = '') {
  return wx[val ? '_setStorage' : '_removeStorage']({
    key: config.storage.sessionKey,
    data: val
  })
}

/**
 * 获取本地token
 */
function getLocalToken() {
  return wx._getStorage({
      key: config.storage.sessionKey
    })
    .then(res => res.data)
    .catch(err => {
      logger.warn(err)
      return null
    })
}

/**
 * 设置/移除 本地user info
 * @param  {} val       token值
 */
function setLocalUser(val = '') {
  return wx[val ? '_setStorage' : '_removeStorage']({
    key: config.storage.userKey,
    data: val
  })
}

/**
 * 获取本地user info
 */
function getLocalUser() {
  return wx._getStorage({
      key: config.storage.userKey
    })
    .then(res => res.data)
    .catch(err => {
      logger.warn(err)
      return null
    })
}

/**
 * 返回页面栈上的页面，并设置相关数据
 * @param  {String | Number} name       待返回页面的name，或者页面栈的delta
 * @param  {Objecy} data={}             返回页面的待设置的data数据
 */
function back(name = '', data = {}) {
  return new Promise((resolve, reject) => {
    if (!name) {
      return reject()
    }
    const pages = getCurrentPages()
    let len = pages.length
    let target = null
    data.fromBack = true
    if (typeof name === 'number') {
      target = pages[len - 1 - name]
      if (target) {
        return reject()
      }
      target.setData(data)
      return wx._navigateBack(name).then(resolve, reject)
    }
    while (len--) {
      let cur = pages[len]
      if (cur && cur.name === name) {
        target = cur
        break
      }
    }
    if (!target) {
      return reject()
    }
    target.setData(data)
    return wx._navigateBack({
      delta: pages.length - 1 - len
    }).then(resolve, reject)
  })
}


/**
 * 防抖函数，适用于输入框input的检索，屏幕的拖拽等
 * @param  {Function} fn                防抖回调
 * @param  {Number}   [delta=0]         回调触发时间
 * @param  {Boolean}  [immediate=false] 是否立即触发回调
 * @return {Function}                   防抖函数包装的函数
 */
const debounce = (fn, delta = 0, immediate = false) => {
  let can = true
  let timer = null
  return function () {
    if (immediate) {
      if (can) {
        fn.call(this, ...arguments)
        can = false
      }
      clearTimeout(timer)
      timer = setTimeout(() => {
        can = true
        fn.call(this, ...arguments)
      }, parseInt(delta))
    } else {
      clearTimeout(timer)
      timer = setTimeout(() => {
        fn.call(this, ...arguments)
      }, parseInt(delta))
    }
  }
}

module.exports = {
  noop,
  isPhoneNo,
  isEmptyObject,
  formatLocation,
  showModal,
  setLocalToken,
  getLocalToken,
  setLocalUser,
  getLocalUser,
  back,
  debounce,
  formatTime,
  formatDate
}
